<template>
  <div id="panel">
    <div class="canvas_container">
    </div>

    <div>
      <button class="btn" @click="preview(500)">预览</button>
      <button class="btn" @click="save">下载</button>
      <button class="btn" @click="clear">清理</button>
      <button class="btn" style="margin-top: 5px;border-color:red;" @click="oneClickToSave"
        title="测试：小鸭卡次卡批量生成">批量小鸭卡</button>
    </div>

    <h5>🎨 <span id="xycoordinates"></span></h5>
  </div>
</template>

<script setup>
import { inject, reactive, watch } from "vue";
import Draw from "../../utils/canvasTools";
import { saveAs } from "file-saver";
import { FTY_DIGITAL_CARD_TEMPLATE_DATA, FTY_SPORT_POSTER_TEMPLATE_DATA } from '../const'

let { canvasId, width, height, radius, dpr } = defineProps(["canvasId", "width", "height", "radius", "dpr"]);
let emit = defineEmits(["updateCoods"]); //暴露更新坐标事件

let helpLine = inject("helpLine");
let drawConfig = inject("drawConfig");
let exportConfig = inject("exportConfig");
let canvasRect = reactive({
  left: 0,
  top: 0,
});
let dw = null;

/**
 * 自动预览效果的场景：
 * - 在元素表单编辑：新增、修改、删除
 * - 在画布上点击：将坐标同步给元素表单选中项
 */
watch(() => drawConfig.value, (newV) => {
  preview(10)
}, {
  deep: true,
})

function cnvs_getCoordinates(e) {
  let x = e.clientX;
  let y = e.clientY;
  let pX = Math.round((x - canvasRect.left));
  let pY = Math.round((y - canvasRect.top));
  document.getElementById("xycoordinates").innerHTML = `坐标：（${pX},${pY}）`

  // 发送坐标
  emit("updateCoods", { x: pX, y: pY });
}

function cnvs_clearCoordinates() {
  document.getElementById("xycoordinates").innerHTML = "";
}

function initCanvas() {
  let canvasContainerEl = document.querySelector('.canvas_container');
  let canvasProps = {
    id: canvasId,
    width: width,
    height: height,
    radius: 16,
    dpr: dpr,
    backgroundColor: "white",
  }

  // 初始化canvas
  dw = new Draw(canvasContainerEl, canvasProps);
  dw.clearCanvas();

  // 给canvas元素增加事件
  dw.canvas.addEventListener("click", cnvs_getCoordinates);
  dw.canvas.addEventListener("mouseout", cnvs_clearCoordinates);

  // 获取canvas元素位置
  let domRect = dw.canvas.getBoundingClientRect();
  canvasRect = { left: domRect.left, top: domRect.top };

  FTY_SPORT_POSTER_TEMPLATE_DATA.map((item) => {
    item.options.des = item.des;
    delete item.des;
    return item;
  });
  localStorage.setItem("config", JSON.stringify(FTY_SPORT_POSTER_TEMPLATE_DATA));

  // 测试
  // draw({shapes: FTY_SPORT_POSTER_TEMPLATE_DATA });
}

setTimeout(() => {
  initCanvas();
}, 1000);

function save() {
  let imgUrl = document.getElementById(canvasId).toDataURL("image/png");
  saveAs(imgUrl, `${+new Date()}.png`);
  return;
  var imgEl = new Image();
  imgEl.src = imgUrl;
  imgEl.width = width;
  imgEl.height = height;
  imgEl.onload = function () {
    document.getElementById("panel").appendChild(imgEl);
  };
}

function draw(configs, delay = 500) {
  dw.create(configs, delay).then((res, err) => {
    if (err) {
      console.log('绘制报错信息：', err)
    }
    console.log("绘制完成");
    if (helpLine.value) {
      drawLines();
    }
  });
}

function drawLines() {
  console.log('绘制辅助线')
  let shapes = [];
  let gap = Math.ceil(width / 3);
  for (let i = gap; i < width; i = i + gap) {
    shapes.push({
      type: "line",
      options: {
        sx: i,
        sy: 0,
        ex: i,
        ey: height,
        width: 1,
        isClosure: false,
        color: "#f5f5f5",
      },
    });
  }
  for (let j = gap; j < height; j = j + gap) {
    shapes.push({
      type: "line",
      options: {
        sx: 0,
        sy: j,
        ex: width,
        ey: j,
        width: 1,
        isClosure: false,
        color: "#f5f5f5",
      },
    });
  }
  dw.create({ shapes, isClear: false });
}

function preview(delay = 500) {
  exportConfig();
  draw({ shapes: drawConfig.value }, delay);
}

async function oneClickToSave(e) {
  const cId = canvasId;

  for (let i = 1; i <= 5; i++) {
    // 动态注入数据
    let drawData = { shapes: [] }
    FTY_DIGITAL_CARD_TEMPLATE_DATA.map(item => {
      if (item.options.des == '小程序码') {
        item.options.url = `https://img.fatiaoya.com/device/treadmill_${i}.jpg`
      }

      if (item.options.des == '兑换码') {
        item.options.text = `DAKBG${i}`
      }

      drawData.shapes.push(item);
    })

    let fileName = `小鸭卡_次卡${i}`;

    await dw.create(drawData, 300);
    console.log("绘制 done!");

    await sleep(300);

    let imgUrl = document.getElementById(cId).toDataURL("image/png");
    saveAs(imgUrl, `${fileName}.png`);
    console.log('保存 done!')

    await sleep(300);
  }
}

function sleep(ms = 300) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

function clear() {
  dw.clearCanvas();
}
</script>
<style lang="less" scoped>
.canvas_container {
  box-shadow: inset 0 0 2px #d8d8fa;

  canvas {
    display: block;
  }
}

.btn {
  margin: 0 4px;
}
</style>